@http.route(['/eroad_bracelet/agent/<int:agent_id>/doctorlist',
    '/eroad_bracelet/agent/<int:agent_id>/doctorlist/<state>',
],type = 'http', auth='user')

def agent_doctorlist(self, req, agent_id=-1,state = None, **kw):
    render_data = self._get_default_render_data(req)
    registry = req.registry
    eba_obj = registry.get('eroad.bracelet.agent')
    
    #demo doctor
    ebd_obj = registry['eroad.bracelet.agent']
    demo_ids = ebd_obj.search(req.cr,SUPERUSER_ID, [('is_demo','=',True)])
    
    agent = eba_obj.browser(req.cr, SUPERUSER_ID, agent_id)
    
    if agent:
        agent_id = agent[id']
        doctors = []
        state_value = -1
        if state =='inactive':
            state_value =4
        else:
            state_value = 1
        
        for doct in agent.doctor_ids:
            if state_value<0 or doct.status == state_value:
                doctors.append(doct)
            elif 4==state_value and doct.status!=1:
                doctors.append(doct)
        
        if demo_ids:
            for demo_doctor in ebd_obj.browse(req.cr,SUPERUSER_ID, demo_ids):
                if state_value <0 or demo_doctor.status == state_value:
                    doctors.insert(0,demo_doctor)
                elif 4 ==state_value and demo_doctor.status!=1:
                    doctors.insert(0,demo_doctor)
    
    render_data.update({'page':{'title':'易康智眠','header':'医生列表','state':state},
                        'result':{
                            'agent':agent,
                            'data':doctors
                        }
            })
    return env.get_template("agent_doctor_list.html").render(render_data)
    
    
def _retrieve_doctor_qr_code(qy_id):
    try:
        if qy_id:
            wx = gzwechat_sdk.WbChatPublic(appid = conf.CORPID, appsecret=conf.CORPSECRET)
            qrcode_dic = {'action_name':'QR_LIMIT_STR_SCENE','action_info':{'scene':{"scene_str":qy_id}}}
            qrcode = wx.create_qrcode(qrcode_dic)
            if qrcode:
                req = wx.show_qrcode(qrcode['ticket'])
                return req
    except:
        pass
    return None
    

class eroad_bracelet_wx_controller(http.Controller):
    
    @http.route(['/eroad_bracelet/patient/doctorlist'],type='http',auth='user')
    def doctorlist(self, req, patient_id=-1,**kw):
        patient_id = self._get_patient_id_in_wx(req)
        return werkzeug.utils.redirect('/eroad_bracelet/patient/%d/doctorlist'%patient_id)
    
    @http.route(['/eroad_bracelet/patient/doctor_json_list'],type='http',auth='user)
    def patient_doctor_json_list(self, req, patient_id=-1,**kw):
        patient_id = self._get_patient_id_in_wx(req)
        return werkzeug.utils.redirect('/eroad_bracelet/patient/%d/reportlist'%patient_id)
    
    
    
    
class agent_department_rank_json(http.Controller):
    @http.route('/agentdepartmentrank/new',type='http',auth='user',cors='*')
    def agentdepartmentrank_new(self, req, **kw):
        method = req.httprequest.method
        if method =='GET' or method== 'POST':
            agentid = req.params.get('agentid')
            pn = req.params.get('page')
            if (png==''):pn=0
            if (pn is None):pn=0
            pn = int(pn)
            if pn<0:pn=1
            
            ps = req.params.get('limit')
            if (ps==''):pn=0
            if (ps is None): ps=0
            ps = int(ps)
            if ps<=0: ps=10
            
            pc=0
            registry = req.registry
            
            # get the Pharmaceutical companies
            getfactorysql = 'select factory_id from eroad_bracelet_agent where id=%s' %agentid
            with registry.cursor() as cr:
                cr.execute(countsql)
                pc = cr.dictfetchall()[0]['count']
            
            if factoryid:
                ranksql = """
                    select * from (select * ,（select count(distinct active) from agent_department_rank_new_view wherw active>t1.active and factory_id=%s)+1 as rank from agent_department_rank_new_view t1 where name<>'' and factory_id=%s order by active desc) t2 where t2.rank<6 order by t2.rank """ %(factoryid, factoryid)
                
                with registry.cursor() as cr:
                    cr.execute(ranksql)
                    agent_rank_lists = cr.dictfetchall()
                
                doctorjson = ''
                
                for rank in agent_rank_lists:
                    temp ='{"mc":"%s", "agency":"%s","active":"%s", "percent":"%s%%"}' %(rank['rank'], rank['agency'], rank['agency'], rank['name'],rank['active'],rank['percent'])
                    
                    if doctorjson!='':
                        doctorjson = doctorjson +',' +temp
                    else:
                        doctorjson = "{'mc':'0','agency':'','name':'','active':'0','percent':''}"
                        
                    success ='true'
                    
                    
                    html = '{"success":"%s","totalcount":"%s","pn":"%s","ps":"%s","title":"代表分组排行榜","header":"代表分组排行榜","data":[%s]}' %(success, pc, pn, ps, doctorjson)
                    return request.make_response(html,{
                        'Cache-Control':'no-cache',
                        'content-Type':'text/html; charset=utf-8',
                        'Access-Control-Allow-Origin':'*',
                        'Orign':'*',
                        'Access-Control-Allow-Methods':'GET,POST',
                        'Access-Control-Allow-Headers':'Refer, Accept,Origin,User-Agent'
                    })
        else:
            return "{%s}" %(method)
            
    @http.route('/agent/team/rank',type='http',auth='user')
    def agent_team_rank(self, req, **kw):
        '''
            参数：agentid
            功能：代表团的排行榜
            说明：重写目的：
                1、取消sql视图的做法
                2、目前不同药厂但是相同组名的团队会出错
            '''
        agent_id = int(kw.get('agentid',0))
        if agent_id !=0:
            agent_obj = req.registry['eroad.bracelet.agent']
            agent = agent_obj.browse(req.cr,SUPERUSER_ID, agent_id)
            if agent.factory_id:
                factory_id = agent.factory_id.id
                agent_teams = agen_obj.search_read(req.cr, SUPERUSER_ID,[('factory_id','=', factory_id),('status','=',1)], fields=['agency'])
                teams = list(set([agent_team['agency'] for agent_team in agent_teams if agent_team['agency']]))
                result_data = []
                for i in xrange(len(teams)):
                    all_doctors=0
                    active_doctors =0
                    name=''
                    team_agent = agent_obj.browse(req.cr,SUPERUSER_ID, agent_obj.search(req.cr,SUPERUSER_ID,[('agency','=',teams[i]),('status','=',1)]))
                    for j in xrange(len(team_agent)):
                        all_doctors += len(team_agent[j].doctor_ids)
                        if team_agent[j].is_leader:
                            name = team_agent[j].name
                        for k in xrange(len(team_agent[j].doctor_ids)):
                            if team_agent[j].doctor_ids[k].status ==1:
                                active_doctors +=1
                    result_data.append({'name':name,'agency':teams[i],'active':active_doctors,'percent':'%d%%' %(int(active_doctor*100/all_doctors))})
                result_data = sorted(result_data, key=operator.itemgetter('active'), reverse=True)
                for i in xrange(len(result_data)):
                    result_data[i]['mc'] = i+1
            else:
                result_data = {'mc':'0','agency':'','name':'','active':'0';'percent':''}
                
            html ={
                'success':True,
                'data':result_data
            }
        else:
            html = {
                'success':False
            }
            
        
        return simplejson.dump(html)
                    
                
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    